﻿namespace LP
{
    using System;
    using System.Collections.Generic;

    public abstract class AbsModuleMgr<T> : Singleton<T>, ILifecycle, IFixedUpdate, IUpdate where T : class
    {
        private Dictionary<Type, AbsModule> modules = new Dictionary<Type, AbsModule>();

        public virtual void OnInit()
        {
            RegModules();
        }

        public abstract void RegModules();

        public virtual void OnDestroy()
        {
            foreach (var item in modules.Values)
            {
                item.OnDestroy();
            }
            modules.Clear();
        }

        public virtual void OnFixedUpdate(float delta)
        {
            foreach (var item in modules.Values)
            {
                item.OnFixedUpdate(delta);
            }
        }

        public virtual void OnUpdate(float delta)
        {
            foreach (var item in modules.Values)
            {
                if (item.IsUpdate)
                {
                    item.OnUpdate(delta);
                }
            }
        }

        public TM RegModule<TM>() where TM : AbsModule
        {
            Type type = typeof(TM);
            TM module = default;
            if (!modules.ContainsKey(type))
            {
                module = Activator.CreateInstance(type, true) as TM;
                modules.Add(type, module);
                module.OnInit();
            }
            return module;
        }

        public void UnRegModule<TM>() where TM : AbsModule
        {
            Type type = typeof(TM);
            if (modules.TryGetValue(type, out AbsModule module))
            {
                module.OnDestroy();
                modules.Remove(type);
            }
        }

        public void UnRegModule(AbsModule module)
        {
            Type type = default;
            foreach (var item in modules.Keys)
            {
                AbsModule curModule = modules[item];
                if (curModule == module)
                {
                    type = item;
                    break;
                }
            }
            if (type != null)
            {
                module.OnDestroy();
                modules.Remove(type);
            }
        }

        public TM RetriveModule<TM>() where TM : AbsModule
        {
            TM ret = default;
            Type type = typeof(TM);
            if (modules.TryGetValue(type, out AbsModule module))
            {
                ret = module as TM;
            }
            return ret;
        }

        public virtual void OnInitFinish()
        {
            foreach (var item in modules.Values)
            {
                item.OnInitFinish();
            }
        }
    }
}